﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Collections.ObjectModel;
using PeteBrown.ConferenceTrivia.Model;
using System.Xml.Linq;
using System.Linq;
using System.Windows.Threading;

namespace PeteBrown.ConferenceTrivia.Services
{
    public class TwitterService
    {
        private string _hashTag;
        private int _maxTweets;

        private DispatcherTimer _timer = new DispatcherTimer();

        public TwitterService(string hashTag, int maxTweets, TimeSpan pollingInterval)
        {
            _hashTag = hashTag;
            _maxTweets = maxTweets;

            // do initial load
            LoadLatestTweets();

            _timer.Interval = pollingInterval;
            _timer.Tick += new EventHandler(OnPoll);
            _timer.Start();
        }

        void OnPoll(object sender, EventArgs e)
        {
            LoadLatestTweets();
        }


        private ObservableCollection<Tweet> _tweets = new ObservableCollection<Tweet>();
        public ObservableCollection<Tweet> Tweets
        {
            get { return _tweets; }
        }


        private bool _loading = false;
        public void LoadLatestTweets()
        {
            WebClient client = new WebClient();

            client.DownloadStringCompleted += (s, e) =>
                {
                    try
                    {
                        XDocument doc = XDocument.Parse(e.Result);
                        XNamespace ns = "http://www.w3.org/2005/Atom";

                        Random rnd = new Random();

                        //orderby item.Element(ns + "id").Value descending

                        var items = (from item in doc.Descendants(ns + "entry")
                                     orderby rnd.Next(1000)
                                     select new Tweet()
                                     {
                                        ImageUrl = new Uri((
                                            from XElement xe in item.Descendants(ns + "link")
                                            where xe.Attribute("type").Value == "image/png"
                                            select xe.Attribute("href").Value).First<string>()),
                                        Message = item.Element(ns + "title").Value,
                                        Author = item.Element(ns + "author").Element(ns + "name").Value,
                                        Id = item.Element(ns + "id").Value
                                     }).Take<Tweet>(_maxTweets);


                        if (items != null && items.Count() > 0)
                        {
                            // Easiest thing to do for this version is just empty and reload vs. do an in-place update
                            Tweets.Clear();

                            // clean up names (this could have been in the linq statement, but I felt it made it too complex)
                            foreach (Tweet tweet in items)
                            {
                                tweet.Author = tweet.Author.Substring(0, tweet.Author.IndexOf('(') - 1);

                                Tweets.Add(tweet);
                            }

                        }


                    }
                    catch (Exception)
                    {
                        // eat the exception for now
                    }

                    _loading = false;
                };

            if (!_loading)
            {
                _loading = true;
                client.DownloadStringAsync(new Uri("http://search.twitter.com/search.atom?q=" + _hashTag + "&rpp=50"));
            }

        }

    }
}
